package logic

import (
	"context"
	"fmt"
	"liepin/liepin-srv/models/mysql"
	"liepin/liepin-srv/models/redis"

	"liepin/liepin-srv/internal/svc"
	"liepin/liepin-srv/liepin"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录注册一体化
func (l *LoginLogic) Login(in *liepin.LoginRequest) (*liepin.LoginResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Rdb.Get(l.ctx, "sendsms"+in.Account)
	if get.Val() != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误")
	}
	liepinuser := mysql.LiePinUser{
		Account:  in.Account,
		Password: in.Password,
	}
	mysql.DB.Where("account=?", in.Account).Find(&liepinuser)
	if liepinuser.ID == 0 {
		mysql.DB.Create(&liepinuser)
		return nil, fmt.Errorf("用户未注册,自动生成账号")
	}
	if liepinuser.Password != in.Password {
		return nil, fmt.Errorf("密码不正确")
	}
	return &liepin.LoginResponse{
		Id: int64(liepinuser.ID),
	}, nil
}
